/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow 
 */

import React, {Component} from 'react';
import {
    Animated,
    DeviceEventEmitter,
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import SelectTopBtn from "../../../utils/SelectTopBtn";
import PersonalPage from "./PersonalPage";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import EditTax from "./EditTax";
import I18n from "../../../res/language/i18n";
import ViewUtils from "../../../utils/ViewUtils";
import ImagePicker from 'react-native-image-picker';
import IparImageView from "../../../custom/IparImageView";

let pageType = 0;
const photoOptions = {
    //底部弹出框选项
    title: I18n.t('default.selectCamera'),
    cancelButtonTitle: I18n.t('default.cancel'),
    takePhotoButtonTitle: I18n.t('default.camera'),
    chooseFromLibraryButtonTitle: I18n.t('default.photo'),
    quality: 0.72,
    allowsEditing: true,
    maxWidth: 500,
    noData: false,
    storageOptions: {
        skipBackup: true,
        // path: 'images'
    }
};
export default class UserInformation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userIn: true,
            taxInformation: false,
            fadeAnim: new Animated.Value(0),
            userData: this.props.userInfo,
            imageUrl: this.props.userInfo && this.props.userInfo.head_img,
        };

        this.iparNetwork = new IparNetwork();


     }


    componentWillUnmount() {
        this.iparNetwork = null;
    }


    /*tabBtn点击时候开始动画*/
    startAnim() {
        Animated.spring(this.state.fadeAnim, {
            toValue: 0,
            velocity: 4,
            tension: -10,
            friction: 3,
        }).start();
    }




    /**
     * 打开相机
     * */
    cameraAction() {
        ImagePicker.showImagePicker(photoOptions, (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else {
                CommonUtils.showLoading();

                let formData = new FormData();
                formData.append("prefix", this.props.userInfo.rand_id);
                formData.append("file", 'data:image/jpeg;base64,' + response.data);
                formData.append("dir", "user");
                this.iparNetwork.getPostFrom(SERVER_TYPE.imgIpar + 'UploadFile?', formData)
                    .then((result) => {
                        if (result.code === 200) {
                            this.props.userInfo.head_img = result.data.url;
                            this.setState({
                                imageUrl: result.data.url,
                            });
                            this.updateAvatar(this.props.userInfo.head_img);
                        } else {
                            CommonUtils.dismissLoading();
                            DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                        }

                    })
                    .catch((error) => {
                        CommonUtils.dismissLoading();
                        console.log(error);
                        DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    })
            }
        });
    }


    updateAvatar(avatarUrl) {
        let formData = new FormData();
        formData.append('user_id', this.props.userInfo.main_user_id);
        formData.append('head_img', avatarUrl);
        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                console.log(result);
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    DeviceEventEmitter.emit('upDateUserData', result.data);
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            });

    }

    render() {
        let userData = this.state.userData;
        let taxInformation = this.state.taxInformation ? <View style={[StyleUtils.flex, {paddingTop: 8}]}>

            <Text style={[{
                marginTop: 10,
                fontSize: 18,
                color: 'black',
                textAlign: 'left'
            }, StyleUtils.smallFont]}>{I18n.t('default.taxRegion')}</Text>
            <Text
                style={[{
                    marginTop: 4, textAlign: 'left'
                }, StyleUtils.smallFont]}>{userData.tex_area}</Text>


            <Text style={[{
                marginTop: 10,
                fontSize: 18,
                color: 'black',
                textAlign: 'left'
            }, StyleUtils.smallFont]}>{I18n.t('default.taxId')}</Text>
            <Text
                style={[{marginTop: 4, textAlign: 'left'}, StyleUtils.smallFont]}>{userData.personal_tax}</Text>

            {/*编辑用户信息editBn*/}

            {//userData.status === 3 || userData.status === 4 || userData.status === 5 ? null :
                ViewUtils.getEditBtn(() => {
                    this.props.navigator.push({
                        component: EditTax,
                        params: {
                            userData: userData,
                            callback: (result) => {
                                this.setState({userData: result});
                                CommonUtils.saveUserInfo(result);
                            },
                        }
                    })
                })}
            <View style={StyleUtils.lineStyle}/>

        </View> : false;

        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop();

                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                />

                <ScrollView style={StyleUtils.flex}>
                    <View style={{paddingLeft: 16, paddingRight: 16}}>

                        <View style={[StyleUtils.center, styles.headerImageBox]}>
                            <View style={StyleUtils.flex}>

                                <Text numberOfLines={1} style={[{
                                    fontSize: 23,
                                    color: 'black'
                                }, StyleUtils.smallFont]}>{userData.nick_name ? userData.nick_name : userData.user_name}</Text>
                                <Text numberOfLines={1}
                                      style={[{
                                          color: '#585858',
                                          textAlign: 'left',
                                      }, StyleUtils.smallFont]}>{I18n.t('default.hereAreThe')}</Text>
                            </View>

                            <TouchableOpacity
                                activeOpacity={0.6}
                                style={[{
                                    width: 70,
                                    height: 70,
                                }, StyleUtils.center]}
                                onPress={() => {
                                    this.cameraAction()

                                }}
                            >

                                <IparImageView
                                    resizeMode={'cover'}
                                    borderRadius={35}
                                    errorImage={require('../../../res/images/ic_avatar.png')}
                                    width={70}
                                    height={70}
                                    url={this.state.imageUrl}/>


                            </TouchableOpacity>
                        </View>
                        {/*点击btn选择页面*/}
                        <View style={styles.tabBox}>
                            <SelectTopBtn
                                type={this.state.userIn}
                                text={I18n.t('default.personalTitle')}
                                onPress={() => {
                                    this.setState({
                                        userIn: true,
                                        taxInformation: false,
                                    });
                                    this.startAnim();
                                    pageType = 0


                                }}
                            />
                            <SelectTopBtn
                                type={this.state.taxInformation}
                                text={I18n.t('default.taxInfoTitle')}
                                onPress={() => {
                                    this.setState({
                                        userIn: false,
                                        taxInformation: true,

                                    });
                                    this.startAnim();
                                    pageType = 1
                                }}
                            />


                        </View>

                        <Animated.View
                            style={{
                                height: '100%',
                                transform: [{
                                    translateY: this.state.fadeAnim.interpolate({
                                        inputRange: [0, 1],
                                        outputRange: [0, 60]
                                    })
                                },
                                ]
                            }}>
                            {this.state.userIn ? <PersonalPage
                                updateInfo={(userData) => this.setState({
                                    userData: userData,
                                })}
                                userInfo={this.state.userData} {...this.props}/> : true}
                            {taxInformation}
                        </Animated.View>
                    </View>

                </ScrollView>
            </View>
        );
    }


}

const styles = StyleSheet.create({

    tabBox: {
        height: 40,
        borderBottomColor: '#eeeeee',
        borderBottomWidth: 1,
        flexDirection: 'row',
        marginTop: 16,
    },
    headerImageBox: {
        height: 80,
        flexDirection: 'row',
        paddingLeft: 16,
        paddingRight: 16,
        marginTop: 20
    },
    addressTv: {
        marginTop: 14,
        color: '#303030',
        fontSize: 15
    },
    editTv: {
        padding: 8,
        fontSize: 14,
        color: 'gray',
        marginTop: 10,
        textAlign: 'right',
        marginRight: 20
    },
    headerImage: {
        width: 70,
        height: 70,
        borderRadius: 35,
        resizeMode: 'cover',
    }
});